package org.apache.flink.client.deployment;

import org.apache.flink.client.cluster.ClusterClientProvider;
import org.apache.flink.client.cluster.rest.RestClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ConsumerManagerOptions;
import org.apache.flink.util.ERException;
import org.apache.flink.util.Preconditions;

/** A deployment descriptor for an existing cluster. */
public class StandaloneClusterDescriptor implements ClusterDescriptor<StandaloneClusterId> {

    private final Configuration config;

    public StandaloneClusterDescriptor(Configuration config) {
        this.config = Preconditions.checkNotNull(config);
    }

    @Override
    public String getClusterDescription() {
        String host = config.getString(ConsumerManagerOptions.ADDRESS, "");
        int port = config.getInteger(ConsumerManagerOptions.PORT, -1);
        return "Standalone cluster at " + host + ":" + port;
    }

    @Override
    public ClusterClientProvider<StandaloneClusterId> retrieve(
            StandaloneClusterId standaloneClusterId) throws ClusterRetrieveException {
        return () -> {
            try {
                return new RestClusterClient<>(config, standaloneClusterId);
            } catch (Exception e) {
                throw new RuntimeException("Couldn't retrieve standalone cluster", e);
            }
        };
    }

    @Override
    public ClusterClientProvider<StandaloneClusterId> deployCluster(
            ClusterSpecification clusterSpecification) {
        throw new UnsupportedOperationException("Can't deploy a standalone cluster.");
    }

    @Override
    public void killCluster(StandaloneClusterId clusterId) throws ERException {
        throw new UnsupportedOperationException("Cannot terminate a standalone cluster.");
    }

    @Override
    public void close() {
        // nothing to do
    }
}
